package com.itheima.Filter;

import com.itheima.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * TODO
 *
 * @Author mr.wu
 * @Data #{DATE} #{TIME}
 */
@WebFilter(urlPatterns = "/*")
@Component
public class TokenFilter implements Filter{


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse)  servletResponse;
        String path = request.getRequestURI();
        if("/login".equals(path)){
            filterChain.doFilter(servletRequest,servletResponse );
        }
        String token = request.getHeader("token");

        if(token==null){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        try {
            Claims claims = JwtUtil.parseJwt(token);
            Object id = claims.get("id");
            Integer empId =Integer.valueOf( String.valueOf(id));
        } catch (Exception e) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            throw new RuntimeException(e);
        }
        filterChain.doFilter(servletRequest,servletResponse );


    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
